﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using STMS.BLL;
using STMS.Models.DModels;
using STMS.STMSApp.FModels;
using STMS.STMSApp.util;

namespace STMS.STMSApp.store
{
    public partial class StoreListForm : Form
    {
        public StoreListForm()
        {
            InitializeComponent();
        }

        StoreBLL storeBLL = new StoreBLL();
        /// <summary>
        /// 页面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StoreListForm_Load(object sender, EventArgs e)
        {
            checkBox_del.Checked = false;
            txt_storeNameNo.Clear();
            LoadStoreList();
        }

        /// <summary>
        /// 加载仓库信息列表
        /// </summary>
        private void LoadStoreList()
        {
            bool isDel = checkBox_del.Checked;
            string keywords = txt_storeNameNo.Text.Trim();
            dgv_storeList.ShowDgvCols(isDel);//显示操作列
            dgv_storeList.Columns["colAddRegion"].Visible = !isDel;

            //加载仓库数据
            List<StoreInfo> storeList = storeBLL.GetStoreList(keywords, isDel);
            if (storeList.Count > 0)
            {
                SetEnableBtn(true);
                dgv_storeList.AutoGenerateColumns = false;
                dgv_storeList.DataSource = storeList;
            }
            else
            {
                SetEnableBtn(false);
                dgv_storeList.DataSource = null;

            }
        }

        private void SetEnableBtn(bool bShow)
        {
            ucb_del.Enabled = bShow;
            //btn_select.Enabled = bShow;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_select_Click(object sender, EventArgs e)
        {
            LoadStoreList();
        }

        /// <summary>
        /// 新增仓库-------打开仓库信息页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_Click(object sender, EventArgs e)
        {
            ShowStoreInfoForm(1, 0);
        }

        /// <summary>
        /// 打开仓库信息页面 --- 新增、修改
        /// </summary>
        /// <param name="actType"></param>
        /// <param name="storeId"></param>
        private void ShowStoreInfoForm(int actType, int storeId)
        {
            StoreInfoForm storeInfoForm = new StoreInfoForm();
            storeInfoForm.Tag = new FInfoData()
            {
                ActType = actType,
                FId = storeId
            };
            //刷新列表页数据效果  委托，采用事件
            storeInfoForm.ReLoadList += () => LoadStoreList();
            storeInfoForm.StartPosition = FormStartPosition.CenterScreen;
            storeInfoForm.ShowDialog();
        }

        /// <summary>
        /// 打开仓库分区信息页面
        /// </summary>
        /// <param name="actType"></param>
        /// <param name="storeId"></param>
        private void ShowStoreRegionInfoForm(int storeId)
        {
            StoreRegionInfoForm storeRegionInfoForm = new StoreRegionInfoForm();
            storeRegionInfoForm.Tag = new FInfoData()
            {
                ActType = 1,
                FId = storeId
            };
            //刷新列表页数据效果  委托，采用事件
            storeRegionInfoForm.ReLoadStoreList += () => LoadStoreList();
            storeRegionInfoForm.StartPosition = FormStartPosition.CenterScreen;
            storeRegionInfoForm.ShowDialog();
        }
        private void dgv_storeList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var cell = dgv_storeList.Rows[e.RowIndex].Cells[e.ColumnIndex];//当前点击的单元格
            string headText = cell.FormattedValue.ToString();
            StoreInfo store = dgv_storeList.Rows[e.RowIndex].DataBoundItem as StoreInfo;
            switch (headText)
            {
                case "添加分区":
                    //打开添加仓库分区信息页
                    ShowStoreRegionInfoForm(store.StoreId);
                    break;
                case "修改":
                    //打开仓库信息页
                    ShowStoreInfoForm(2, store.StoreId);
                    break;
                case "删除":
                    //执行逻辑删除（假删除）update
                    DeleteStore(store,1);
                    break;
                case "恢复":
                    //恢复（逻辑恢复）
                    DeleteStore(store, 0);
                    break;
                case "移除":
                    //真删除-delete
                    DeleteStore(store, 2);
                    break;
            }
        }

        /// <summary>
        /// 删除、恢复、移除仓库
        /// </summary>
        /// <param name="store"></param>
        /// <param name="delCode"></param>
        private void DeleteStore(StoreInfo store, int delCode)
        {
            //string InfoName = "仓库信息";
            string delName = FormUtil.GetDelName(delCode);

            DialogResult result = MessageBox.Show($"{delName}仓库信息，请谨慎操作！", "提示", MessageBoxButtons.OKCancel);
            if(result == DialogResult.OK)
            {
                bool isDel = false;
                switch (delCode)
                {
                    case 1:
                        //逻辑删除
                        int reDel = storeBLL.LogicDeleteStore(store.StoreId);
                        if(reDel == 1)
                        {
                            //删除成功
                            isDel = true;
                        }
                        else if(reDel == 2)
                        {
                            //该仓库 存在分区
                            MessageBox.Show("该仓库存在分区，不能删除！");
                            return;
                        }
                        else
                        {
                            //删除失败
                            //   逻辑删除时，删除失败，  但是 数据更改了，返回结果错误。
                            //返回  返回的值判断。
                            //MessageBox.Show($"返回值：{reDel}");
                            isDel = false;
                        }
                        break;

                    case 0:
                        //恢复
                        isDel = storeBLL.ReceiveStore(store.StoreId);
                        break;
                    case 2:
                        //真删除
                        isDel = storeBLL.DeleteStore(store.StoreId);
                        break;
                }

                if (isDel)
                {
                    MessageBox.Show($"{delName}仓库信息成功！");
                    LoadStoreList();
                }
                else
                    MessageBox.Show($"{delName}仓库信息失败！");
            }
        }

        /// <summary>
        /// 刷新仓库列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucb_refresh_Click(object sender, EventArgs e)
        {
            checkBox_del.Checked = false;
            LoadStoreList();
            txt_storeNameNo.Clear();
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucb_del_Click(object sender, EventArgs e)
        {
            string msg = "提示";
            //1.初始化一个空的 List<int>
            List<int> storeIds = new List<int>();
            //2.	遍历 DataGridView 的每一行。
            foreach (DataGridViewRow row in dgv_storeList.Rows)
            {
                //3.	获取每行的数据绑定对象 StoreInfo。
                StoreInfo storeInfo = row.DataBoundItem as StoreInfo;
                //4.	获取每行的复选框单元格 DataGridViewCheckBoxCell。
                DataGridViewCheckBoxCell chkCell = row.Cells["colChk"] as DataGridViewCheckBoxCell;
                //5.	检查复选框是否被选中。
                if (chkCell.FormattedValue.ToString() == "True")
                {
                    //6.	如果复选框被选中，将 StoreId 添加到列表中。
                    storeIds.Add(storeInfo.StoreId);
                }
            }
            if(storeIds.Count > 0)
            {
                DialogResult result = MessageBox.Show("你确定要删除选择的仓库信息吗？",$"{msg}",MessageBoxButtons.OKCancel);
                if(result == DialogResult.OK)
                {
                    string reStr = storeBLL.LogicDeleteStore(storeIds);
                    if(reStr == "Y")
                    {
                        MessageBox.Show("选择的仓库信息删除成功！", $"{msg}");
                        LoadStoreList();
                    }
                    else if(reStr.Contains(" (已删除)"))
                    {
                        MessageBox.Show("选择的仓库信息删除失败，请确认所选仓库是否已删除！---编号是："+reStr, $"{msg}");
                        return;
                    }
                    else if (reStr.Length>=1 || reStr!="Y" ||reStr=="0")//存在有分区的仓库
                    {
                        MessageBox.Show("选择的仓库信息删除失败，请确认所选仓库是否有分区！---编号是："+reStr, $"{msg}");
                        return;
                    }
                    else
                    {
                        MessageBox.Show("删除失败！", $"{msg}");
                        return;
                    }
                }
            }
            else
            {
                MessageBox.Show("请至少选择一个仓库！",$"{msg}");
            }
        }
    }
}
